package com.kill.servicescript;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.accessibilityservice.GestureDescription;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.PendingIntent;
import android.graphics.Path;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import androidx.annotation.RequiresApi;

import java.lang.ref.WeakReference;
import java.util.List;

import static com.kill.servicescript.kotlinsrc.GetPacketNameKt.getPacketName;
import static com.kill.servicescript.task.QuTouTiaoTaskKt.onTast;

@RequiresApi(api = Build.VERSION_CODES.N)
public class ScriptServer extends AccessibilityService {
    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
//        String packageName = event.getPackageName().toString();
//        String className = event.getClassName().toString();
//        LogUtil.e(packageName);

//        LogUtil.e("============================================================:"+className);
        onDouYinTask(event);

//        int eventType = event.getEventType();
//        switch (eventType){
//            case AccessibilityEvent.TYPE_VIEW_CLICKED:
//                LogUtil.d("View被点击");
//                break;
//            case AccessibilityEvent.TYPE_VIEW_LONG_CLICKED:
//                LogUtil.d("View被长按");
//                break;
//            case AccessibilityEvent.TYPE_VIEW_SELECTED:
//                LogUtil.d("View被选中");
//                break;
//            case AccessibilityEvent.TYPE_VIEW_FOCUSED:
//                LogUtil.d("View获得焦点");
//                break;
//            case AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED:
//                LogUtil.d("View文本变化");
//                break;
//            case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
//                LogUtil.d("打开了一个PopupWindow，Menu或Dialog");
//                break;
//            case AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED:
//                LogUtil.d("Notification变化");
//                break;
//            case AccessibilityEvent.TYPE_VIEW_HOVER_ENTER:
//                LogUtil.d("一个View进入悬停");
//                break;
//            case AccessibilityEvent.TYPE_VIEW_HOVER_EXIT:
//                LogUtil.d("一个View退出悬停");
//                break;
//            case AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_START:
//                LogUtil.d("触摸浏览事件开始");
//                break;
//            case AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_END:
//                LogUtil.d("触摸浏览事件完成");
//                break;
//            case AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED:
////                LogUtil.d("窗口的内容发生变化，或子树根布局发生变化");
//                break;
//            case AccessibilityEvent.TYPE_VIEW_SCROLLED:
//                LogUtil.d("View滚动");
//                break;
//            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED:
//                LogUtil.d("Edittext文字选中发生改变事件");
//                break;
//            case AccessibilityEvent.TYPE_ANNOUNCEMENT:
//                LogUtil.d("应用产生一个通知事件");
//                break;
//            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED:
//                LogUtil.d("获得无障碍焦点事件");
//                break;
//            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED:
//                LogUtil.d("无障碍焦点事件清除");
//                break;
//            case AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY:
//                LogUtil.d("在给定的移动粒度下遍历视图文本的事件");
//                break;
//            case AccessibilityEvent.TYPE_GESTURE_DETECTION_START:
//                LogUtil.d("开始手势监测");
//                break;
//            case AccessibilityEvent.TYPE_GESTURE_DETECTION_END:
//                LogUtil.d("结束手势监测");
//                break;
//            case AccessibilityEvent.TYPE_TOUCH_INTERACTION_START:
//                LogUtil.d("触摸屏幕事件开始");
//                break;
//            case AccessibilityEvent.TYPE_TOUCH_INTERACTION_END:
//                LogUtil.d("触摸屏幕事件结束");
//                break;
//            case AccessibilityEvent.TYPE_WINDOWS_CHANGED:
//                LogUtil.d("屏幕上的窗口变化事件，需要API 21+");
//                break;
//            case AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED:
//                LogUtil.d("View中的上下文点击事件");
//                break;
//            case AccessibilityEvent.TYPE_ASSIST_READING_CONTEXT:
//                LogUtil.d("辅助用户读取当前屏幕事件");
//                break;
//            default:
//                LogUtil.e(eventType+"------------------------------------------------------");
//                break;
//        }
    }

    @Override
    public void onInterrupt() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //无障碍服务请求激活“触摸浏览”功能
//        getServiceInfo().flags = AccessibilityServiceInfo.FLAG_REQUEST_TOUCH_EXPLORATION_MODE;
        initService();
        LogUtil.i("开始运行服务");
        myHandler.sendEmptyMessageDelayed(HANDLERRUN,100);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        myHandler.removeMessages(HANDLERRUN);
    }

    // ==============================================================================================
    // Handler 控制服务一直运行
    //
    private final static int HANDLERRUN = 10001;
    private MyHandler myHandler = new MyHandler(this);
    private static class MyHandler extends Handler {
        final WeakReference<ScriptServer> serverWeakReference;
        public MyHandler(ScriptServer scriptServer){
            serverWeakReference = new WeakReference<>(scriptServer);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            ScriptServer scriptServer = serverWeakReference.get();
            if(scriptServer!=null){
                switch (msg.what){
                    case HANDLERRUN:
                        scriptServer.huadong();
                        LogUtil.i("循环任务");
                        scriptServer.myHandler.sendEmptyMessageDelayed(HANDLERRUN,1000);
                        break;
                }
            }
        }
    }
    //
    // END
    // =============================================================================================


    //https://blog.csdn.net/zhoukongxiao/article/details/79068425?utm_source=blogxgwz8
    //https://www.it610.com/article/1280731328131645440.htm
    // ==============================================================================================
    // 业务逻辑
    //
    private void onQTTTask(AccessibilityEvent event){
        if(!getPacketName("趣头条").equals(event.getPackageName().toString())){
            return;
        }

        onListTask();

    }
    AccessibilityNodeInfo rootInActiveWindow;
    private void initService() {
        GestureDescription.Builder builder = new GestureDescription.Builder();
        Path path = new Path();
        path.moveTo(540, 1800);
        path.lineTo(540, 200);
        gestureDescription = builder.addStroke(new GestureDescription.StrokeDescription(path, 20, 500)).build();
    }
    private GestureDescription gestureDescription;
    private void onDouYinTask(AccessibilityEvent event){
//        String packageName = event.getPackageName().toString();
//        String className = event.getClassName().toString();
//        LogUtil.e(packageName);
//        LogUtil.e(event.getEventType()+"====");

        //被监听的界面
        if (getPacketName("快手").equals(event.getPackageName().toString())) {
            rootInActiveWindow = getRootInActiveWindow();
            isHuadong =  true;
//            LogUtil.e("====================是快手app");
        }
    }

    boolean isHuadong = false;
    long huadongtime = 0;
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void huadong(){
        try {
            if(System.currentTimeMillis()-huadongtime>5000 && isHuadong){
                huadongtime = System.currentTimeMillis();
                LogUtil.e("开始滑动");
                dispatchGesture(gestureDescription, new GestureResultCallback() {
                    @Override
                    public void onCompleted(GestureDescription gestureDescription) {
                        super.onCompleted(gestureDescription);
                        LogUtil.e( "----模拟手势成功-----");
                    }

                    @Override
                    public void onCancelled(GestureDescription gestureDescription) {
                        super.onCancelled(gestureDescription);
                        LogUtil.e("----模拟手势失败-----");
                    }
                }, null);

            }
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.e(e.toString());
        }
    }

    @SuppressLint("NewApi")
    private void onListTask(){
        AccessibilityNodeInfo nodeInfo = this.getRootInActiveWindow();
        List<AccessibilityNodeInfo> listName = nodeInfo.findAccessibilityNodeInfosByText("任务");
        performClick(listName);

        //com.jifen.qukan:id/wy
        List<AccessibilityNodeInfo> listId = findNodesById("com.jifen.qukan:id/wy ");
        performClick(listId);
    }
    //
    // END
    // =============================================================================================


    /**
     * 根据View的ID搜索符合条件的节点,精确搜索方式;
     * 这个只适用于自己写的界面，因为ID可能重复
     * api要求18及以上
     * @param viewId
     */
    public List<AccessibilityNodeInfo> findNodesById(String viewId) {
        AccessibilityNodeInfo nodeInfo = getRootNodeInfo();
        if (nodeInfo != null) {
            if (Build.VERSION.SDK_INT >= 18) {
                return nodeInfo.findAccessibilityNodeInfosByViewId(viewId);
            }
        }
        return null;
    }
    /**
     * 根据Text搜索所有符合条件的节点, 模糊搜索方式
     */
    public List<AccessibilityNodeInfo> findNodesByText(String text) {
        AccessibilityNodeInfo nodeInfo = getRootNodeInfo();
        if (nodeInfo != null) {
            return nodeInfo.findAccessibilityNodeInfosByText(text);
        }
        return null;
    }

    //点击
    private boolean performClick(List<AccessibilityNodeInfo> nodeInfos) {
        if (nodeInfos != null && !nodeInfos.isEmpty()) {
            AccessibilityNodeInfo node;
            for (int i = 0; i < nodeInfos.size(); i++) {
                node = nodeInfos.get(i);
                // 获得点击View的类型
//                AccessibilityLog.printLog("View类型：" + node.getClassName());
                // 进行模拟点击
                if (node.isEnabled()) {
                    return node.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                }
            }
        }
        return false;
    }

    //返回
    public boolean clickBackKey() {
        return this.performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
    }

    private AccessibilityNodeInfo getRootNodeInfo(){
        return this.getRootInActiveWindow();
    }
}
